package org.dromara.third.convert.gatherPeople.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.BusinessServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidateUtil;
import org.dromara.system.domain.AlarmArea;
import org.dromara.system.domain.GatherPeople;
import org.dromara.system.mapper.AlarmAreaMapper;
import org.dromara.system.mapper.GatherPeopleMapper;
import org.dromara.third.auth.beans.constans.ExceptionEnum;
import org.dromara.third.auth.common.auth.TokenThreadLocal;
import org.dromara.third.auth.util.AESUtil;
import org.dromara.third.convert.gatherPeople.dto.GatherPeopleDTO;
import org.dromara.third.convert.gatherPeople.validator.GatherPeopleValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
@RestController
@Slf4j
@RequestMapping("/api/v1")
public class ConvertGatherPeopleController {

    @Autowired
    private GatherPeopleMapper gatherPeopleMapper;

    @Autowired
    private AlarmAreaMapper alarmAreaMapper;

    @PostMapping("/gatherPeople")
    @Transactional
    public R<Void> addGatherPeople(@RequestBody String jsonReq) {
        String orgCode = TokenThreadLocal.getThreadLocal();
        GatherPeopleDTO gatherPeopleDTO;
        try {
            String decrypt = AESUtil.decrypt(jsonReq);
            gatherPeopleDTO = JSONObject.parseObject(decrypt, GatherPeopleDTO.class);
        } catch (Exception e) {
            log.info("解析参数异常");
            throw new BusinessServiceException(ExceptionEnum.AuthException06.getCode(), ExceptionEnum.AuthException06.getMessage());
        }
        // 校验参数
        List<String> errorMessageList = new ArrayList<>();
        ValidateUtil.validate(errorMessageList, gatherPeopleDTO, new GatherPeopleValidator());
        if (!CollectionUtils.isEmpty(errorMessageList)) {
            String errorMessage = StringUtils.join(errorMessageList, ",");
            throw new BusinessServiceException(ExceptionEnum.AuthException06.getCode(), errorMessage);
        }
        List<AlarmArea> alarmAreaList = new ArrayList<>();
        GatherPeople gatherPeople = assemblePersonLocationData(orgCode, gatherPeopleDTO, alarmAreaList);
        int count = gatherPeopleMapper.countWithOutDelFlag(gatherPeople.getId());
        if (count == 0) {
            gatherPeopleMapper.insert(gatherPeople);
            alarmAreaMapper.insertBatch(alarmAreaList);
        } else {
            gatherPeopleMapper.updateWithOutDelFlag(gatherPeople);
            alarmAreaMapper.delete(new LambdaQueryWrapper<AlarmArea>().eq(AlarmArea::getGatherPeopleId, gatherPeople.getId()));
            alarmAreaMapper.insertBatch(alarmAreaList);
        }
        return R.ok();
    }

    private GatherPeople assemblePersonLocationData(String orgCode, GatherPeopleDTO dto, List<AlarmArea> alarmAreaList) {
        GatherPeople gatherPeople = new GatherPeople();
        try {
            gatherPeople.setId(dto.getId());
            gatherPeople.setAlarmTime(DateUtils.parseDate(dto.getAlarmTime()));
            gatherPeople.setAlarmNumber(dto.getAlarmNumber());
            gatherPeople.setAlarmLevel(dto.getAlarmLevel());
            gatherPeople.setGatheringAreaName(dto.getGatheringAreaName());
            dto.getAlarmArea().forEach(alarmAreaDTO -> {
                AlarmArea alarmArea = new AlarmArea();
                alarmArea.setGatherPeopleId(dto.getId());
                alarmArea.setName(alarmAreaDTO.getName());
                alarmArea.setPersonId(alarmAreaDTO.getPersonId());
                alarmArea.setLongitude(alarmAreaDTO.getLongitude());
                alarmArea.setLatitude(alarmAreaDTO.getLatitude());
                alarmAreaList.add(alarmArea);
            });
            gatherPeople.setDelFlag(Long.parseLong(dto.getDelFlag()));
            gatherPeople.setCreateDept(Long.parseLong(dto.getCreateDept()));
            gatherPeople.setCreateBy(Long.parseLong(dto.getCreateBy()));
            gatherPeople.setCreateTime(DateUtils.parseDate(dto.getCreateTime()));
            gatherPeople.setUpdateBy(Long.parseLong(dto.getUpdateBy()));
            gatherPeople.setUpdateTime(DateUtils.parseDate(dto.getUpdateTime()));
            gatherPeople.setTenantId(orgCode);
        } catch (Exception e) {
            throw new BusinessServiceException(ExceptionEnum.AuthException07.getCode(), "组装人员聚集报警信息异常");
        }
        return gatherPeople;
    }
}
